import { defineStore } from 'pinia'
import { ref } from 'vue'
import {computed} from 'vue'
import { useUserStore } from './userStore'
import {getCart,insertCart,deleteCart} from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
    const userStore=useUserStore()
    const isLogin=computed(()=>userStore.userInfo.token)
  // 1. 定义state - cartList
  const cartList = ref([])
  // 2. 定义action - addCart
  //获取购物车列表
  const updateNewList=async()=>{
    const res=await getCart()
    cartList.value=res.result
  }
  //添加购物车
  const addCart = async(goods) => {
    const {skuId,count}=goods
    // console.log('添加', goods)
    if(isLogin.value){
        //登录之后加入购物车逻辑
        await insertCart({skuId,count})
       updateNewList()
    }else{
        const item = cartList.value.find((item) => goods.skuId === item.skuId)
        if (item) {
          // 找到了
          item.count++
        } else {
          // 没找到
          cartList.value.push(goods)
        }
      }
    }
    // 添加购物车操作
    // 已添加过 - count + 1
    // 没有添加过 - 直接push
    // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
  
  //删除购物车
  const delCart=async(skuId)=>{
    if(isLogin.value){
       await deleteCart([skuId])
      updateNewList()
    }else{
        cartList.value=cartList.value.filter(item=>item.skuId===item.id)
    }
  }
  //清除购物车
  const clearCart=()=>{
    cartList.value=[]
  }
  //单选功能
  const singleCheck=(skuId,selected)=>{
    const item=cartList.value.find(item =>item.skuId===skuId)
    item.selected=selected
  }
  //全选功能
  const allCheck=(selected)=>{
    cartList.value.forEach(item=>item.selected=selected)
  }
  //计算属性
//   1.总的数量
    const countTotal=computed(()=>cartList.value.reduce((sum,item)=>sum+item.count,0))
    // 2.总价
    const totalPrice=computed(()=>cartList.value.reduce((sum,item)=>sum+item.count * item.price,0).toFixed(2))
    const isAll=computed(()=>cartList.value.every(item=>item.selected))
    //已选择数量
    const selectedCount=computed(()=>cartList.value.filter(item=>item.selected).reduce((sum,item)=>sum+item.count,0))
    //已选择合计
    const selectedTotal=computed(()=>cartList.value.filter(item=>item.selected).reduce((sum,item)=>sum+item.count * item.price,0))
  return {
    cartList,
    addCart,
    delCart,
    updateNewList,
    singleCheck,
    allCheck,
    clearCart,
    selectedCount,
    selectedTotal,
    isAll,
    countTotal,
    totalPrice
  }
}, {
  persist: true,
})
